package handler

import (
	"animal-mng-sys/cache"
	"animal-mng-sys/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	desc := c.PostForm("desc")
	author := c.PostForm("author")
	data := models.Article{

		Title:  title,
		Desc:   desc,
		Author: author,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
		"data": data,
	})
	return
}
func Del(c *gin.Context) {
	id := c.PostForm("id")
	err := models.DB.Where("id = ?", id).Delete(&models.Article{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
func List(c *gin.Context) {
	var list []models.Article

	redis_list_key := "redis_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if cacheData == "" {
		models.DB.Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}
